package db

import (
	"database/sql"
	"user-server/src/model"
)

func QueryUserByUsername(username string) (*model.UserInfo, error) {
	sql := "SELECT username, password, nickname, profile FROM user_info_tab WHERE username = ?"
	rows, err := db.Query(sql, username)
	//defer rows.Close()
	if err != nil {
		return nil, err
	}
	var u model.UserInfo
	for rows.Next() {
		var userName string
		var password string
		var nickName string
		var profile string
		if err := rows.Scan(&userName, &password, &nickName, &profile); err != nil {
			return nil, err
		}
		u.Username = userName
		u.Password = password
		u.Nickname = nickName
		u.Profile = profile
	}
	return &u, err
}

func UpdateByUsername(username, nickname, profile string) (bool, error) {
	var (
		result sql.Result
		err    error
	)
	if nickname != "" && profile != "" {
		sql := "UPDATE user_info_tab SET profile = ?, nickname = ? WHERE username = ?"
		result, err = db.Exec(sql, profile, nickname, username)
	}
	if nickname != "" {
		sql := "UPDATE user_info_tab SET nickname = ? WHERE username = ?"
		result, err = db.Exec(sql, nickname, username)
	}
	if profile != "" {
		sql := "UPDATE user_info_tab SET profile = ? WHERE username = ?"
		result, err = db.Exec(sql, profile, username)
	}
	rowsAffected, err := result.RowsAffected()
	return rowsAffected == 1, err
}
